<?php

require_once 'models/ArticleManager.php';
require_once 'controllers/Controller.php';

class ArticleController extends Controller
{
	private $_am;
	
	public function __construct() {
		parent::__construct();
		$this->_am = new ArticleManager($this->_bdd);
	}
	
	

	public function vendre() {
        if(isset($_POST['categorie']) && isset($_POST['ville']) && isset($_POST['name']) && isset($_POST['description']) && isset($_POST['prix']) && isset($_POST['couleur'])) {
            $array = array('categorie'=>$_POST['categorie'],'user'=>$_SESSION['email'],'ville'=>$_POST['ville'], 'name' => $_POST['name'], 'description' => $_POST['description'], 'prix' => $_POST['prix'], 'couleur' => $_POST['couleur']);
            $a = new Article($array);
            $this->_am->add($a);
		$id= $a->getId()[0];
	    	$target_path = "uploads/".$id.".jpg";
 
		//echo $target_path;
		if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
		   // echo "The file ".  basename( $_FILES['uploadedfile']['name'])." has been uploaded";
		} else{
		    echo "There was an error uploading the file, please try again!";
		}
            //$vendre = 0;
        }
        else if (isset($_POST['submit'])){
            $vendre = 1;
        }
		include 'views/article.php';
	}

	public function rechercher() {
		if(isset($_POST['requete'])){
			$requete = $_POST['requete'];
			$types=null;
			$descriptions=null;
			$w;
			if(preg_match('/type ?= ?"[^"]*"/', $requete, $types, 0)){
				$requete = preg_replace('/ type ?= ?"([^"]*) "/'," name LIKE '%$1%'", $requete);
				$types = preg_replace('/type ?= ?"([^"]*)"/','$1', $types);
				
			}
			if(preg_match('/description ?= ?"[^"]*"/', $requete, $descriptions, 0)){
				$requete = preg_replace('/ description ?= ?"([^"])*"/','', $requete);
				$descriptions = preg_replace('/description ?= ?"([^"])*"/','$1', $descriptions);
			}
			if(preg_match('/WHERE ?AND/', $requete, $w, 0)){
				$requete = preg_replace('/WHERE ?AND/','WHERE', $requete);
			}
			//echo $requete;
			$articles = $this->_am->execRequete($requete);
			$articles_trie = array();
			foreach ($articles as $article){
				$score = 0;
				foreach ($types as $type){
					$score += substr_count($article->name, $type);
					$score += substr_count($article->description, $type);
				}
				foreach ($descriptions as $description){
					$score += substr_count($article->name, $description);
					$score += substr_count($article->description, $description);
				}
				$articles_trie[] = array('score' => $score, 'article' => $article);
			}
			array_multisort($articles_trie['score'], SORT_ASC,SORT_STRING);
		}
		include "views/resultat_recherche.php";
	}

}

?>
